package com.uh.rds.tester.standalone;


import com.uh.rds.testing.config.TestConfig;
import com.uh.rds.testing.config.TestConfigManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.*;


/**
 *   - id: "ClusterDataScaleTest"
 *     name: "ClusterDataScaleTest"
 *     description: "集群间添加减少分片"
 *     configs:
 *       # 数据量
 *       dataCount: 200
 *       # 插入数据与数据之间的间隔时间
 *       validateInterval: 5
 *       # 集群节点
 *       endpoints:
 *         - ip: 192.168.0.81
 *           port: 6379
 *         - ip: 192.168.0.81
 *           port: 6380
 *         - ip: 192.168.0.81
 *           port: 6381
 *         - ip: 192.168.0.81
 *           port: 6382
 *         - ip: 192.168.0.81
 *           port: 6383
 *         - ip: 192.168.0.81
 *           port: 6384
 */
public class ClusterDataScaleTest {


    private Logger logger = LoggerFactory.getLogger(ClusterDataScaleTest.class);

    private TestConfig conf;

    private List<Map<String, Object>> endpoints;

    /**
     * 初始化测试环境
     */
    public void init(){
        logger.info("ClusterDataScaleTest init ...");
        conf = TestConfigManager.getTestConfig("ClusterDataScaleTest");
        endpoints =conf.getList("endpoints");
    }


    /**
     * 插入数据
     */
    public void test() throws InterruptedException {
        init();

        // 设置集群节点的地址和端口
        Set<HostAndPort> jedisClusterNodes = new HashSet<>();
        for (Map<String, Object> server : endpoints) {
            String ip = (String) server.get("ip");
            Integer port = (Integer) server.get("port");
            jedisClusterNodes.add(new HostAndPort(ip, port));
        }
        // 创建 JedisCluster 实例，这里不设置密码和超时时间，可以根据需要设置
        JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes);
        //清空数据
        jedisCluster.flushAll();

        String keyPrefix = "mikey";

        Integer size = 0;

        for(int i=0 ; i<conf.getInteger("dataCount"); i++) {
            Thread.sleep(conf.getInteger("validateInterval"));
            String key = keyPrefix + i;
            String value = UUID.randomUUID().toString().replaceAll("-", "");

            try{
                jedisCluster.set(key, value);
                size ++;
            } catch (Exception e) {
                //节点变化，重新获取节点连接
                logger.info("集群分片发送变化，重新获取节点分片信息......");
                init();
                jedisCluster.set(key, value);

                size ++;
            }
            logger.info("key: " + key + " value: " + value);
        }

        logger.info("一共插入数据条数：" + size);

        // 关闭连接池
        jedisCluster.close();

    }


    public static void main(String[] args) throws Exception {
        ClusterDataScaleTest test = new ClusterDataScaleTest();
        test.test();
    }
}
